﻿using Loaf.Beans;
using Loaf.Tools;
using Loaf.ViewModels;
using Loaf.自定义控件.Controls;
using Prism.Commands;
using System.Windows;

namespace Loaf.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : CustomWindow
    {
        public Context Context { get; set; }

        public MainWindow(Context context)
        {
            InitializeComponent();

            Context = context;

            this.Loaded += OnLoaded;

            //重写退出事件
            this.CloseWindowCommand = new DelegateCommand(() =>
            {
                Context.WriteContext();
                this.Close();
            });

        }

        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            var size = SystemTool.GetWindowSize();
            var center = new Point(Context.AppSetting.Left + Context.AppSetting.Width / 2, Context.AppSetting.Top + Context.AppSetting.Height / 2);
            if (center.X < 0 || center.X > size.X || center.Y < 0 || center.Y > size.Y)
            {
                Context.AppSetting.Left = 50;
                Context.AppSetting.Top = 50;
            }

            SystemTool.Regist(this, Context.AppSetting.HotkeyModifiers, Context.AppSetting.Hotkey, OpenMainWindow);

            (this.DataContext as MainWindowModel)?.OnLoaded();

            Context.MainWindow = this;

            if (Context.ReaderWindow != null)
            {
                this.Visibility = Visibility.Collapsed;
                Context.ReaderWindow.Visibility = Visibility.Visible;
                Context.ReaderWindow.Activate();
            }
        }

        /// <summary>
        /// 打开活动的窗体
        /// </summary>
        public void OpenMainWindow()
        {
            if (Context.BookSetting.LastBook != null)
            {
                try
                {
                    Context.ReaderWindow.Visibility = Visibility.Visible;
                    Context.ReaderWindow.Activate();
                }
                catch
                {
                    Context.BookSetting.LastBook = null;
                    this.Visibility = Visibility.Visible;
                    this.Activate();
                }
            }
            else
            {
                this.Visibility = Visibility.Visible;
                this.Activate();
            }
        }

    }
}
